package com.tianqi.tools;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.weixin.sdk.api.AccessToken;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.utils.HttpUtils;

/**
 * 生成专属二维码
 * @author zhbin
 * @date 2018年9月30日 下午4:20:16
 */
public class Qrcode {

	// 临时二维码
	public static final String QR_SCENE = "QR_SCENE"; //-1
	// 永久二维码
	public static final String QR_LIMIT_SCENE = "QR_LIMIT_SCENE";//0
	// 永久二维码(字符串)
	public static final String QR_LIMIT_STR_SCENE = "QR_LIMIT_STR_SCENE";//1
	// 创建二维码
	public static final String CREATE_TICKET_PATH = "https://api.weixin.qq.com/cgi-bin/qrcode/create";
	// 通过ticket换取二维码
	public static final String SHOW_QRCODE_PATH = "https://mp.weixin.qq.com/cgi-bin/showqrcode";
	// 长链接转成短链接
	public static final String WECHAT_SHORT_QRCODE_URL = "https://api.weixin.qq.com/cgi-bin/shorturl";
	 
	public static final String LONG2SHORT = "long2short";

	
	public String createForeverTicket(int sceneId) {
		AccessToken accessTokenApi = AccessTokenApi.getAccessToken();
		String accessToken = accessTokenApi.getAccessToken();
		Map<String, Integer> intMap = new HashMap<>();
		intMap.put("scene_id", sceneId);
		Map<String, Map<String, Integer>> mapMap = new HashMap<>();
		mapMap.put("scene", intMap);
		Map<String, Object> paramsMap = new HashMap<>();
		paramsMap.put("action_name", QR_LIMIT_SCENE);
		paramsMap.put("action_info", mapMap);
		String data = JSON.toJSONString(paramsMap);
		data = HttpUtils.post(CREATE_TICKET_PATH+"?access_token="+accessToken, data);

		JSONObject parseObject = JSONObject.parseObject(data);
		String longUrl = parseObject.get("url").toString();
		
		return longUrl;
	}
	/**
	 * 长链接转短链接
	 * 
	 * @param accessToken
	 * @param longUrl
	 *            长链接
	 * @return
	 */
	public String toShortQRCodeurl( String longUrl) {
		AccessToken accessTokenApi = AccessTokenApi.getAccessToken();
		String accessToken = accessTokenApi.getAccessToken();
		TreeMap<String, String> params = new TreeMap<>();
		params.put("access_token", accessToken);
		Map<String, Object> paramsMap = new HashMap<>();
		paramsMap.put("action", LONG2SHORT);
		paramsMap.put("long_url", longUrl);
		String data = JSON.toJSONString(paramsMap);
		String post = HttpUtils.post(WECHAT_SHORT_QRCODE_URL+"?access_token="+accessToken, data);
		return post;
	}

	 
}
